import adminRoutes from '@/modules/admin/router'
import NotFound from '@/views/404/index.vue'
import Dashboard from '@/views/dashboard/index.vue'
import Home from '@/views/home/index.vue'
import Layout from '@/views/layout/index.vue'
import Login from '@/views/login/index.vue'
import Register from '@/views/register/index.vue'
import MessageBoard from '@/views/messageBoard/index.vue'
import MultiDevice from '@/views/multiDevice/index.vue'
import Test from '@/views/test/index.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: Home,
      },
      {
        path: '/message-board',
        name: 'MessageBoard',
        component: MessageBoard,
      },
      {
        path: '/multi-device',
        name: 'MultiDevice',
        component: MultiDevice,
      },
      {
        path: '/dashboard',
        name: 'dashboard',
        component: Dashboard,
        meta: { login: true },
      },
      {
        path: '/login',
        name: 'login',
        component: Login,
      },
      {
        path: '/register',
        name: 'register',
        component: Register,
      },
    ],
  },
  ...adminRoutes,
  {
    path: '/test',
    name: 'test',
    component: Test,
    // meta: { login: true,role: 'admin' },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
  },
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach(async (to) => {
  const { useLoginStore } = await import('/src/stores/loginStore.js')
  const loginStore = useLoginStore()

  if (to.meta.login) {
    // 检查是否需要登录
    if (!loginStore.loginInfo) {
      ElMessage('请登录后操作')
      let returnUrl = '';
      if (to.path.startsWith('/admin')) {
        returnUrl = `/admin/login?redirect=${to.fullPath}`
      } else {
        returnUrl = `/login?redirect=${to.fullPath}`
      }
      return returnUrl;
    }
    // 检查用户角色是否有权限访问该页面
    if (to.meta.role && to.meta.role !== loginStore.loginInfo.role) {
      ElMessage('抱歉，您没有权限访问该资源')
      return '/home'
    }
    // 进一步检查用户是否有权限访问管理系统
    // if (to.path.startsWith('/admin') && loginStore.loginInfo.role !== 'admin') {
    //   ElMessage('抱歉，您没有权限访问管理系统')
    //   return '/home'
    // }
  } else {
    if (loginStore.loginInfo) {
      switch (to.path) {
        case '/login':
          ElMessage('您已经登录过了')
          return ''
        case '/admin/login':
          ElMessage('您已经登录过了')
          return '/admin'
      }
    }
  }
  return true
})

export default router
